//
// Created by 倪加奇 on 17-1-23.
// Email: drnijq@126.com
// Copyright (c) 2017 杭州威固网络科技有限公司. All rights reserved.
//

#include "tcp_echo_server.h"

tcp_echo_server::tcp_echo_server(boost::asio::io_service &io_server, unsigned short listen_port)
        : _accepter(io_server, tcp::endpoint(tcp::v4(), listen_port)), _ns_listen_port(listen_port) {
    start_accept();
}

void tcp_echo_server::start_accept() {
    tcp_echo_connetion::pointer new_connetion =
            tcp_echo_connetion::create_pointer(_accepter.get_io_service());

    _accepter.async_accept(new_connetion->socket(),
                           boost::bind(&tcp_echo_server::handle_accept, this,
                                       new_connetion,
                                       boost::asio::placeholders::error()));
}

void tcp_echo_server::handle_accept(tcp_echo_connetion::pointer new_connection,
                                    const boost::system::error_code &error) {
    if (boost::system::errc::success == error) {
        new_connection->first_start();
        new_connection->start();
    }
    start_accept();
}
